package com.cdream.basic.thread;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author cdream
 * @date 2022/2/12
 */
@Slf4j(topic = "reentrant_lock")
public class ReentrantLockExample {
    private static ReentrantLock lock = new ReentrantLock();
    // 公平锁，本意是解决饥饿问题，但tryLock同样可以解决
    // private static ReentrantLock lock = new ReentrantLock(true);
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            try {
                log.debug("尝试获取锁");
                lock.lockInterruptibly();
                // 避免无限制的等待下去
                // lock.tryLock();
                // 增加waitSet的方式
                // Condition condition = lock.newCondition();
                // condition.await();
                // condition.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
                log.debug("获取失败");
                return;
            }
            try {
                log.debug("获取到锁了");
            } finally {
                lock.unlock();
            }
        },"t1");
        lock.lock();
        t1.start();
        Thread.sleep(1000);
        log.debug("打断t1");
        t1.interrupt();
    }
}
